import type { IClientOptions, MqttClient } from 'mqtt';

import mqtt from 'mqtt';

const mqttConfig = {
  keepalive: 60,
  clean: true,
  reconnectPeriod: 30_000, // 自动重连
  connectTimeout: 30_000, // 连接超时（单位毫秒）
  rejectUnauthorized: false, // 是否允许不安全的连接
};

class MqttService {
  private client: MqttClient | null = null;

  // Connect to MQTT Broker
  connect(brokerUrl: string, customOptions: IClientOptions): void {
    const options: IClientOptions = {
      ...mqttConfig, // 使用默认配置
      ...customOptions, // 合并传入的自定义配置
    };

    this.client = mqtt.connect(brokerUrl, options);

    this.client.on('connect', () => {
      console.log('connected');
    });

    this.client.on('message', (topic, message) => {
      console.log('Received message:', topic, message.toString());
    });

    this.client.on('error', (err) => {
      console.error('MQTT Connection error:', err);
    });
  }

  // Disconnect from the broker
  disconnect(): void {
    this.client?.end(() => {
      console.log('MQTT Disconnected');
    });
  }

  // Publish a message to a topic
  publish(topic: string, message: string): void {
    this.client?.publish(topic, message, (err) => {
      if (err) {
        console.error('Publish error:', err);
      } else {
        console.log(`Message sent to topic: ${topic}`);
      }
    });
  }

  // Subscribe to a topic
  subscribe(topic: string) {
    this.client?.subscribe(topic, (err) => {
      if (err) {
        console.error('Subscription error:', err);
      } else {
        console.log(`Subscribed to topic: ${topic}`);
      }
    });
  }
}

export default new MqttService();
